//
//  HMRefreshControl.swift
//  01-自定义下拉刷新控件
//
//  Created by apple on 17/2/7.
//  Copyright © 2017年 apple. All rights reserved.
//

import UIKit
// 抽取控件的高度
private let HMRefreshControlH: CGFloat = 50
// 自定义下拉刷新控件的状态
enum HMRefreshControlType: String{
    case normal = "正常中"
    case pulling = "下拉中"
    case refreshing = "刷新中"
}

class HMRefreshControl: UIControl {
    
    // 记录列表
    var scrollView: UIScrollView?
    // 时实记录刷新控件的状态
    var refreshType: HMRefreshControlType = .normal{
        didSet{
            // rawValue 通过枚举名得到枚举值
            messageLabel.text = refreshType.rawValue
            switch refreshType {
            case .normal:
                // 设置箭头动画
                UIView.animate(withDuration: 0.25, animations: { 
                    // 恢复原状
                    self.pullRefreshImageView.transform = CGAffineTransform.identity
                })
                
                // 判断我们上一个状态是否是刷新中
                if oldValue == .refreshing {
                    UIView.animate(withDuration: 0.25, animations: {
                        self.scrollView!.contentInset.top = self.scrollView!.contentInset.top - HMRefreshControlH

                    }, completion: { (_) in
                        // 显示箭头 和 风火轮停止动画
                        self.indicatorViews.stopAnimating()
                        self.pullRefreshImageView.isHidden = false
                    })
                }
                
            case .pulling:
                // 设置箭头动画
                UIView.animate(withDuration: 0.25, animations: { 
                    self.pullRefreshImageView.transform = CGAffineTransform(rotationAngle: CGFloat(-3*M_PI))
                })
            case .refreshing:
                UIView.animate(withDuration: 0.25, animations: { 
                    self.scrollView!.contentInset.top = self.scrollView!.contentInset.top + HMRefreshControlH
                    // 隐藏箭头 和 风火轮开始动画
                    self.pullRefreshImageView.isHidden = true
                    self.indicatorViews.startAnimating()
                }, completion: { (_) in
                    // 告知外界刷新数据
                    self.sendActions(for: UIControlEvents.valueChanged)
                })
            }
        }
    }

    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -HMRefreshControlH, width: UIScreen.main.bounds.width, height: HMRefreshControlH))
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 供外界调用的方法 -> 停止刷新
    func endRefreshing(){
        // 把 控件的状态改为正常
        refreshType = .normal
    }
    
    // 监听当前对象将要加载在身上
    override func willMove(toSuperview newSuperview: UIView?) {

        // 判断newSuperview 是否为nil 而且是否可以滚动
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        
        // 开始赋值
        self.scrollView = scrollView
        // 自定义下拉刷新控件监听TableView 的属性变化 -> KVO
        //1.注册观察者
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil)
    }
    // 2.观察者中实现
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
//        print(self.scrollView?.contentOffset.y)
        // 得到当前 判断的临界值(-114)
        // 计算临界值
        
        let maxY = self.scrollView!.contentInset.top + HMRefreshControlH
        let contentOffsetY = self.scrollView!.contentOffset.y
        // 判断使用是否在拖动中
        if self.scrollView!.isDragging {
//            print("拖动中")
                /*
             - 正常和下拉中
                - 如果Y >= -114  && 状态为下拉中 -> 正常中
                - 如果Y < - 114 && 状态为正常中 -> 下拉中
             
             */

            // 正常的
            if contentOffsetY >= -maxY && refreshType == .pulling{
//                print("正常中")
                refreshType = .normal
            }else if contentOffsetY < -maxY && refreshType == .normal {
                // 下拉中
//                print("下拉中")
                refreshType = .pulling
            }

        }else {
            //- 如果当前的状态为下拉中 -> 刷新中
            if refreshType == .pulling {
                refreshType = .refreshing
            }
        }
        
    }
    
    //MARK: - 设置视图
    private func setupUI(){
        // 背景颜色
        backgroundColor = UIColor.orange
        // 添加控件
        addSubview(messageLabel)
        addSubview(pullRefreshImageView)
        addSubview(indicatorViews)
        // 添加约束
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        
        pullRefreshImageView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: pullRefreshImageView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: pullRefreshImageView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        
        indicatorViews.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: indicatorViews, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: indicatorViews, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
 
    }
    
    //MARK: - 懒加载控件
    // 文字
    private lazy var messageLabel: UILabel = {
        let lab = UILabel()
        lab.font = UIFont.systemFont(ofSize: 14)
        lab.textAlignment = .center
        lab.textColor = UIColor.white
        lab.text = "正常中"
        return lab
    }()
    // 箭头
    private lazy var pullRefreshImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    // 风火轮
    private lazy var indicatorViews: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    
    deinit {
        // 3. 移除观察者
        self.scrollView!.removeObserver(self, forKeyPath: "contentOffset")
    }

}
